<template>
  <div>
    <Card>
      <Button type="primary" @click="showAddModal" class="mr10"
        >添加食物热量数据</Button
      >
      <Button
        type="primary"
        :loading="refreshLoading"
        @click="refreshEvent"
        shape="circle"
        icon="md-refresh"
        class="fr"
      ></Button>
      <Select v-model="searchTypeValue" class="searchInputClass">
        <Option
          v-for="item in searchType"
          :value="item.value"
          :key="item.value"
          >{{ item.label }}</Option
        >
      </Select>
      <Input
        v-model="searchKeyWord"
        placeholder="请输入搜索关键字"
        suffix="ios-search"
        class="searchKeyWordInputClass"
      />
    </Card>
    <Row style="margin-bottom: 20px">
      <Col :xs="24" :sm="24" :md="24" :lg="24">
        <Card>
          <Tables
            ref="tables"
            editable
            v-model="searchData"
            :columns="columns"
            :loading="loading"
            :border="true"
            size="large"
          />
        </Card>
        <!-- <Page
          :total="num"
          @on-change="changePage"
          show-sizer
          show-elevator
          show-total
          :page-size="pageSize"
          :page-size-opts="$store.state.pageSizeArray"
          @on-page-size-change="changePageSize"
          style="margin-top: 12px; float: right"
        /> -->
      </Col>
    </Row>
    <Modal
      title="添加食物热量数据"
      v-model="addModal"
      :styles="{ top: '50px' }"
      @on-ok="addDataEvent"
    >
      <Form :model="addData" :label-width="80">
        <FormItem label="食物名称：" prop="name">
          <Input
            v-model="addData.name"
            maxlength="15"
            type="text"
            placeholder="请输入食物名称，字数不超过15字。"
          ></Input>
        </FormItem>
        <FormItem label="食物类型：" prop="type">
          <Select v-model="addData.type" class="inputWidth200">
            <Option
              v-for="item in $store.state.foodType"
              :value="item.value"
              :key="item.title"
              >{{ item.title }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="食物热量：" prop="heat">
          <Input-number
            :max="9999"
            :min="0"
            v-model="addData.heat"
            autoFocus
            :step="1"
          ></Input-number
          >（每100克）
        </FormItem>
        <FormItem label="备注：" prop="name">
          <Input
            v-model="addData.remark"
            maxlength="100"
            show-word-limit
            type="textarea"
            :rows="4"
            placeholder="请输入食物备注，字数不超过100字。"
          ></Input>
        </FormItem>
      </Form>
    </Modal>

    <Modal
      title="修改数据"
      v-model="editTodoListModal"
      :styles="{ top: '50px' }"
      @on-ok="editDataEvent"
    >
      <Form :model="editData" :label-width="80">
        <FormItem label="食物名称：" prop="name">
          <Input
            v-model="editData.name"
            maxlength="15"
            type="text"
            placeholder="请输入食物名称，字数不超过15字。"
          ></Input>
        </FormItem>
        <FormItem label="食物类型：" prop="type">
          <Select v-model="editData.type" class="inputWidth200">
            <Option
              v-for="item in $store.state.foodType"
              :value="item.value"
              :key="item.title"
              >{{ item.title }}</Option
            >
          </Select>
        </FormItem>
        <FormItem label="食物热量：" prop="heat">
          <Input-number
            :max="9999"
            :min="0"
            v-model="editData.heat"
            autoFocus
            :step="1"
          ></Input-number
          >（每100克）
        </FormItem>
        <FormItem label="备注：" prop="name">
          <Input
            v-model="editData.remark"
            maxlength="100"
            show-word-limit
            type="textarea"
            :rows="4"
            placeholder="请输入食物备注，字数不超过100字。"
          ></Input>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import Tables from "_c/tables";
import {
  getFoodHeatData,
  addFoodHeatData,
  deleteFoodHeatData,
  editFoodHeatData,
} from "@/api/content/health/foodheat.js";
export default {
  name: "tables_page",
  components: {
    Tables,
  },
  data() {
    return {
      refreshLoading: false,
      addData: { name: "", heat: null,remark:"" },
      addModal: false,
      editData: {},
      editTodoListModal: false,
      num: 0,
      columns: [
        { title: "食物名称", key: "name", width: 200 },
        { title: "食物类型", key: "type", width: 200 },
        { title: "热量（每100克）", key: "heat", width: 200 },
        { title: "备注", key: "remark" },
        {
          title: "操作",
          width: 200,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.editData = params.row;
                      this.editData.heat = parseInt(this.editData.heat);
                      this.editData.type = this.formatFoodType(
                        this.editData.type,
                        "title"
                      )[0]["value"];
                      this.showEditModal();
                    },
                  },
                },
                "修改"
              ),
              h(
                "Poptip",
                {
                  props: {
                    confirm: true,
                    type: "error",
                    size: "large",
                    title: "你确定要删除吗?",
                  },

                  on: {
                    "on-ok": () => {
                      this.deleteDataEvent(params.row);
                    },
                    "on-cancel": () => {
                      this.$Message.info("您取消了删除");
                    },
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "warning",
                      },
                      style: {
                        marginRight: "5px",
                      },
                    },
                    "删除"
                  ),
                ]
              ),
            ]);
          },
        },
      ],
      tableData: [],
      num: 0,
      pageCurrent: 1,
      pageSize: 10,
      loading: true,
      searchType: [
        {
          label: "食物名称",
          value: "name",
        },
        {
          label: "食物类型",
          value: "type",
        },
        {
          label: "热量",
          value: "heat",
        },
      ],
      searchTypeValue: "",
      searchKeyWord: "",
    };
  },
  methods: {
    //添加食物热量数据
    addDataEvent() {
      this.addData.heat = parseInt(this.addData.heat);
      if (!this.requireFormData(this.addData)) {
        return;
      } else {
        addFoodHeatData(this.addData).then((res) => {
          if (res.data.code == 0) {
            this.getData(this.pageCurrent, this.pageSize);
            this.addData.name = "";
            this.addData.heat = null;
            this.addData.remark = "";
            this.$Message.success("您成功添加了一条热量数据.");
          } else if (res.data.code == 1010) {
            this.$Message.error("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "您添加食物热量数据失败了，错误原因：" + res.data.msg
            );
          }
        });
      }
    },
    editDataEvent() {
      if (!this.requireFormData(this.editData)) {
        return false;
      } else {
        editFoodHeatData(this.editData)
          .then((res) => {
            if (res.data.code == 0) {
              this.getData(this.pageCurrent, this.pageSize);
              this.$Message.success("您成功修改了一条热量数据.");
            } else if (res.data.code == 1010) {
              this.$Message.warning("您的登录状态已失效，请您重新登录.");
              this.$router.push("/login");
            } else {
              this.$Message.error(
                "您修改食物热量数据失败了，错误原因：" + res.data.msg
              );
            }
          })
          .catch((err) => {
            this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
          });
      }
    },
    requireFormData(data) {
      if (!data.name || data.name.length > 15) {
        this.$Message.warning(
          "您输入的食物名称格式错误，字数在1-15之间，请重新输入."
        );
        return false;
      } else if (!data.type || data.type.length > 99) {
        this.$Message.warning("您选择的食物类型格式错误，请重新选择.");
        return false;
      } else if (data.heat < 1 || data.heat.length > 999) {
        this.$Message.warning(
          "您输入的热量格式错误，数值应在在1-999之间，请重新输入."
        );
        return false;
      } else {
        return true;
      }
    },
    formatFoodType(data, value) {
      return this.$store.state.foodType.filter((item) => {
        return item[value] == data;
      });
    },
    //删除食物热量数据
    deleteDataEvent(row) {
      deleteFoodHeatData(row.id)
        .then((res) => {
          if (res.data.code == 0) {
            this.tableData.splice(row["_index"], 1);
            this.$Message.success("您成功删除了一个食物热量数据.");
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "您删除食物热量数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },
    refreshEvent() {
      this.refreshLoading = true;
      this.getData(this.pageCurrent, this.pageSize);
    },
    //打开添加页面
    showAddModal() {
      this.addModal = true;
    },

    //打开修改页面
    showEditModal() {
      this.editTodoListModal = true;
    },
    //获取表格食物热量数据
    getData(page, pageNum) {
      this.loading = true;
      getFoodHeatData(page, pageNum)
        .then((res) => {
          if (res.data.code == 0) {
            this.num = res.data.num;
            this.tableData = res.data.data;
            for (let index = 0; index < this.tableData.length; index++) {
              this.tableData[index].type = this.formatFoodType(
                this.tableData[index].type,
                "value"
              )[0]["title"];
            }
            this.loading = false;
            this.refreshLoading = false;
          } else if (res.data.code == 1010) {
            this.$Message.warning("您的登录状态已失效，请您重新登录.");
            this.$router.push("/login");
          } else {
            this.$Message.error(
              "自动获取数据失败了，错误原因：" + res.data.msg
            );
          }
        })
        .catch((err) => {
          this.$Message.error("服务器异常，请稍后重试.错误原因：" + err);
        });
    },

    //第几页食物热量数据
    changePage(index) {
      this.pageCurrent = index;
      this.getData(this.pageCurrent, this.pageSize);
    },

    //每页显示食物热量数据
    changePageSize(size) {
      this.pageSize = size;
      this.getData(this.pageCurrent, this.pageSize);
    },
  },
  created() {
    this.pageSize = this.$store.state.pageSize;
    this.getData(this.pageCurrent, this.pageSize);
  },
  computed: {
    searchData() {
      if (!this.searchKeyWord) {
        return this.tableData;
      }
      return this.tableData.filter((item) => {
        return item[this.searchTypeValue].indexOf(this.searchKeyWord) !== -1;
      });
    },
  },
};
</script>
<style scope>
</style>